<?php
/**
 * 订单类
 */
namespace app\v2\controller;

use think\Request,
    app\v2\model\Pay as Paymodel,
    app\v2\model\Order as OrderModel,
    app\common\model\paymentOrder,
    app\common\model\Payment,
    app\v2\model\Apply,
    app\v2\model\UserInfo,
    app\v2\model\UserBankCard,
    think\Db,
    app\v2\logic\Repayment;
use app\common\model\HcPay;
use fuiou\FuiouApi;
    
class Order extends Base{
    public function __construct(){
        parent::__construct();
        date_default_timezone_set('Asia/Shanghai');
        $this->orderModel = model('order');
    }

    // 支付异步回调
    public function notify(Request $request){
        $data = $request->post();
        $PayModel =  new Paymodel;
        file_put_contents('111.txt', json_encode($data));
        echo $PayModel->notice($data);
    }

    // 还款成功提示页面
    public function successPage(){
        header('Location:'.config('domainpath')['h5']);
        die; 
    }

    //还款成功之后的操作
    public function payAction() {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid   = $isLogin['uid'];
        $data  = $this->orderModel->payAction($this->param['type'], $uid);
        if(!$data){
            return resultArray(['error' =>$this->orderModel->getError()]);
        }
        return resultArray(['data' => '操作成功']);
    }

    // 创建订单支付链接
    // 接收参数：order_number申请单号  pay_type付款类型(1:全款 2:续期)
    public function createorder()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $data  = $this->orderModel->createorder($this->param);
        if(!$data){
            return resultArray(['error' =>$this->orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 支付记录
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-10-18T11:31:14+0800
     * @return   [type]                          [description]
     */
    public function payRecord()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid   = $isLogin['uid'];
        $page  = $this->param['page'];
        $limit = $this->param['limit'];
        $data  = $this->orderModel->payRecord($page, $limit, $uid);
        if($data===false){
            return resultArray(['error' =>$this->orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 查询订单支付结果
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-13T15:54:02+0800
     */
    public function queryPay()
    {
        $no_order = $this->param['no_order'];
        $OrderModel = new OrderModel;
        $order_info = $OrderModel->where(["no_order"=>$no_order])->find();
        if(!$order_info) {
            return resultArray(["error"=>"没有获取到订单信息"]);
        }
        $Paymodel=  new Paymodel;
        $res = $Paymodel->queryPay($order_info); 
        if(!$res){
            return resultArray(["error"=>$Paymodel->getError()]);
        }       
        return resultArray(["data"=>$res]);
    }
    /**
     * 银行卡 bin 信息查询
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-13T15:54:02+0800
     */
    public function BinQuery()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid   = $isLogin['uid'];

        $param = $this->param;
        $card_no = $param['bank_card_number'];
        // $card_no = "6236681930005397672";

        $Paymodel=  new Paymodel;
        $res = $Paymodel->BinQuery($card_no); 
        if(!$res){
            return resultArray(["error"=>$Paymodel->getError()]);
        }       
        return resultArray(["data"=>$res]);
    }
    /**
     * 银行卡列表
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-14T11:15:06+0800
     * @return      
     */
    public function bankcardbindlist()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid   = $isLogin['uid'];
        $Paymodel=  new Paymodel;
        // offset 偏移量 默认0  不分页
        $res = $Paymodel->bankcardbindlistQuery($uid,$offset = "0"); 
        if(!$res){
            return resultArray(["error"=>$Paymodel->getError()]);
        }       
        return resultArray(["data"=>$res]);        


    }    

    /**
     * 绑定银行卡
     * @author   yhq <934797303@qq.com>
     * @DateTime 2018-03-17T17:17:01+0800
     * @return   [type]                   [description]
     */
    public function bankcardbind()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid = $isLogin['uid'];
        $param = $this->param;
        if(empty($param['name'])||empty($param['id_card'])||empty($param['bank_card_number'])){
            return resultArray(['error' =>'缺少参数']); 
        }

        $UserInfoModel = new UserInfo;
        // 再次绑卡 验证是否本人银行卡
        $UserInfo = $UserInfoModel->where('uid', $uid)->field('id_card,rand_code,insurance,phone')->find();
        if(!empty($UserInfo['id_card'])){
            if($param['id_card'] != $UserInfo['id_card']){    
                return resultArray(["error"=>'请检查身份证号码']);      
            }
        }

        // 限制同一身份证绑定多个账号
        $map['id_card'] = $param['id_card'];
        $map['uid']     = ['neq', $uid];
        $userInfo = $UserInfoModel->where($map)->field('phone')->find();
        if(!empty($userInfo)){
            $str = $userInfo['phone'];
            $phone = substr($str,0,3).'****'.substr($str,-4);
            return resultArray(['error' =>"该身份证已经被{$phone}绑定"]); 
        }

        // 三要素认证
        $url = 'http://api.qhweidai.com/api/Threecredit';
        $para = [
            'name'     => $param['name'],
            'idNumber' => $param['id_card'],
            'bankCard' => $param['bank_card_number'],
            'channel'  => config('operator_channel')
        ];

        $res = curlPost($url,$para);
        $res = json_decode($res, true);

        if($res['code']!=200){
            return resultArray(['error' =>'绑定失败001']);
        }
        if($res['data']['error']!=200){
            return resultArray(['error' => $res['data']['msg']]);
        }
        switch ($res['data']['tianji_api_rong360_bankcard3Item_response'][0]['checkStatus']) {
            case 'S':
                //赠送保险
                if($UserInfo['insurance'] == 1) {
                    $project = str_replace(['【', '】'],  ['',''], config('message_prefix'));
                    $postUrl = 'http://121.196.206.97/insurance/appsvr/life/donate';

                    $postData['mobile']     = $UserInfo['phone'];//手机号
                    $postData['idNo']       = $param['id_card'];//身份证
                    $postData['name']       = $param['name'];//姓名
                    $postData['channel']    = 'FA25'; //渠道
                    $postData['remark']     = '勾选赠险/'.$project.'/4000以下/职员/小额信用';//是否贷款
                    $postData['customerIp'] = getClientIP();//ip
                   
                    $insurance = curlPostForm($postUrl,$postData);
                    $insurance = json_decode($insurance, true);
                    $param['insurance'] = $insurance['bizData']['code'];
                }

                $res = $UserInfoModel->allowField(true)->save($param,['uid'=>$uid]);
                if($res!==false){
                    return resultArray(['data' =>'绑定成功']); 
                }
                return resultArray(['data' =>'绑定失败002']);
                break;
            case 'F':
                return resultArray(['error' =>'身份信息不一致']);
                break;
            default:
                return resultArray(['error' =>'未知错误']);
                break;
        }      
    }


    /**
     * 设置默认银行卡
     * @author  llj <just05075@foxmail.com>
     * @date(2017年11月11日17:23:19)
     */
    public function setDefaultBankCard(){

       $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $param = $this->param;
        $param['uid'] = $uid = $isLogin['uid'];

        $UserBankCardModel = new UserBankCard;

        $res = $UserBankCardModel->setDefaultBankCard($param);

        if($res!==false){
            return (["code"=>200,"msg"=>'设置成功!']); 
        }
        return (["code"=>400,"msg"=>$UserBankCardModel->getError()]);
        
    }

    /**
     * 保存银行卡
     * @return [type]        [description]
     */
    public function saveBankCard()
    {
       $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $param = $this->param;
        $param['uid'] = $isLogin['uid'];

        $UserInfoModel = new UserInfo;
        //再次绑卡 验证是否本人银行卡
        $idCard = $UserInfoModel->where('uid', $param['uid'])->value('id_card');
        if($idCard){
            if($param['id_card'] != $idCard){    
                return resultArray(["error"=>'请检查身份证号码']);      
            }
        }

        $Paymodel = new Paymodel;
        $data = $Paymodel->saveBankCard($param);
        if($data){
            return resultArray(['data' => '银行卡'.substr($param['bank_card_number'], -4).'绑定成功']); 
        }
        return resultArray(['error' => $Paymodel->getError()]); 
    }

    
    /**
     * 银行卡解绑
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-14T11:15:06+0800
     * @return      
     */
    public function bankcardunbind()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $param = $this->param;
        $param["uid"] = $isLogin['uid'];
        
        $Paymodel=  new Paymodel;
        $res = $Paymodel->bankcardunbind($param); 
        
        if(!$res){
            return resultArray(["error"=>$Paymodel->getError()]);
        }      
        return resultArray(["data"=>"解绑成功，请稍等片刻"]);        
    } 


    // 打款异步回调接口
    public function notify_payment(){
        $PaymentModle =  new Payment;
        $PaymentModle->async_notice();        
    }    


    //扣款处理
    public function repayment()
    {
        $repayment = new Repayment;
        $repayment->handleRepayment();
    }
    /**
     * [hcQueryOrder 汇潮订单查询]
     * @return [type] [description]
     */
    public function hcQueryOrder()
    {
        if(!isset($this->param['order_number']))
        {
            return resultArray(['error' => '请求参数错误']);
        }

        $order_number = $this->param['order_number'];
        $paymentModel = new HcPay;
        $result = $paymentModel->hcQuery($order_number);
        if(!$result)
        {
            return resultArray(['error' => $paymentModel->getError()]);
        }
        return resultArray(['data' => $result]);


    }
    /**
     * [bindBankCard 富友绑定银行卡]    --废弃使用--
     * @return [type] [description]
     */
    public function bindBankCard()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid = $isLogin['uid'];
        $param = $this->param;
        if(empty($param['userNm'])||empty($param['credtNo'])||empty($param['acntNo'])||empty($param['bankCd'])){
            return resultArray(['error' =>'缺少参数']); 
        }

        $UserInfoModel = new UserInfo;
        // 再次绑卡 验证是否本人银行卡
        $UserInfo = $UserInfoModel->where('uid', $uid)->field('id_card')->find();
        if(!empty($UserInfo['id_card'])){
            if($param['id_card'] != $UserInfo['id_card']){    
                return resultArray(["error"=>'请检查身份证号码']);      
            }
        }

        // 限制同一身份证绑定多个账号
        $map['id_card'] = $param['credtNo'];
        $map['uid']     = ['neq', $uid];
        $userInfo = $UserInfoModel->where($map)->field('phone')->find();
        if(!empty($userInfo)){
            $str = $userInfo['phone'];
            $phone = substr($str,0,3).'****'.substr($str,-4);
            return resultArray(['error' =>"该身份证已经被{$phone}绑定"]); 
        }
        $data['uid']              = $uid;//签约来源
        $data['name']             = $param["userNm"];//业务类型
        $data['id_card']          = $param['credtNo']; //证件号
        $data['bank_card_number'] = $param['acntNo']; //银行卡号
        $data['bind_mob']         = $param['mobileNo']; //手机号
        $data['user_nm']          = $param['bankCd']; //户名
        $data['create_time']      = date('Y-m-d H:i:s'); //
        //更新银行卡状态
        $userBankCard = new UserBankCard;
        $re = $userBankCard->modifyBankCardPackage($data);
        if(!$re)
        {
            return resultArray(['error' => $userBankCard->getError()]);
        }
        return resultArray(['data' => (new FuiouApi)->returnSignaTureParam($param)]);

    }
}
